package com.et.core.broadcast

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import com.et.core.file.Advert
import com.et.logger.ELog
import com.et.logger.TAGS
import org.json.JSONObject

private val pushMessageReceiver = PushMessageReceiver()
private const val ACTION_ADVERT = "com.et.action.advert.change"
private const val ACTION_PAY_TYPE = "com.et.action.pay.change"


fun registerPushMessageReceiver(context: Context) {
    context.registerReceiver(pushMessageReceiver, IntentFilter().also {
        ELog.d(TAGS.vending, "vending:register push message receiver")
        it.addAction(ACTION_PAY_TYPE)
        it.addAction(ACTION_ADVERT)
    })
}

fun unRegisterPushMessageReceiver(context: Context) {
    context.unregisterReceiver(pushMessageReceiver)
}

class PushMessageReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent?) {
        ELog.d(TAGS.vending, "vending:broadcast Receiver:${intent?.getStringExtra("json")}")
        intent?.let {
            when (it.action) {

                ACTION_PAY_TYPE -> {
                    it.getStringExtra("json")?.let { json ->
                        payTypeData.postValue(JSONObject(json).getString("pay_type_set"))
                    }
                }
                ACTION_ADVERT -> {
                    it.getStringExtra("json")?.let { json ->
                        Advert.getInstance().addAdvert(json)
                        context.getSharedPreferences("adv_info", Context.MODE_PRIVATE).edit()
                            .putString("adv", json).apply()
                    }
                }

                else -> {

                }
            }
        }
    }

}